package com.yiba.vpn.utils;

import android.text.TextUtils;
import android.util.SparseIntArray;

import com.yiba.vpn.utils.logger.LogUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * 国内服务Ip管理，后期想办法可以找一个稳定的服务器来做跳板检测
 * 目前是根据后台给的IP来匹配，匹配上就proxy
 */
public class ChinaIpMaskManager {

    static SparseIntArray ChinaIpMaskDict = new SparseIntArray(3000);
    static SparseIntArray MaskDict = new SparseIntArray();

    /**
     * 判断Ip是否是国内的Ip.目前国内IP段是后台给的
     *
     * @param ip
     * @return
     */
    public static boolean isIPInChina(int ip) {
        boolean found = false;
        try {
            for (int i = 0; i < MaskDict.size(); i++) {
                int mask = MaskDict.keyAt(i);
                int networkIP = ip & mask;
                int mask2 = ChinaIpMaskDict.get(networkIP);
                if (mask2 == mask) {
                    found = true;
                    break;
                }
            }
        } catch (Exception e) {
            if (LogUtil.OPEN_LOG) {
                System.out.printf("国内IP代理失败\n", e.toString());
            }
        }
        return found;
    }

    /**
     * 从InputStream里获取国内IP
     *
     * @param inputStream
     */
    public static void loadFromFile(InputStream inputStream) {
        int count = 0;
        try {
            byte[] buffer = new byte[4096];
            while ((count = inputStream.read(buffer)) > 0) {
                for (int i = 0; i < count; i += 8) {
                    int ip = CommonMethods.readInt(buffer, i);
                    int mask = CommonMethods.readInt(buffer, i + 4);
                    ChinaIpMaskDict.put(ip, mask);
                    MaskDict.put(mask, mask);
                    if (LogUtil.OPEN_LOG) {
                        System.out.printf("%s/%s\n", CommonMethods.ipIntToString(ip), CommonMethods.ipIntToString(mask));
                    }
                }
            }
            inputStream.close();
            if (LogUtil.OPEN_LOG) {
                System.out.printf("ChinaIpMask records count: %d\n", ChinaIpMaskDict.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 支持网络获取请求数据
     *
     * @param path
     */
    public static void loadFromUrl(String path) {
    }

    public static void loadFromObject(String ips) {
        try {
            if (!TextUtils.isEmpty(ips)) {
                String[] ipandMask = ips.split("/");
                if (ipandMask.length != 2) {
                    return;
                }
                int ip = CommonMethods.ipStringToInt(ipandMask[0]);
                int mask = CommonMethods.ipStringToInt(IPUtils.getMaskByMaskBit(ipandMask[1]));
                ChinaIpMaskDict.put(ip, mask);
                MaskDict.put(mask, mask);
            }
        } catch (Exception e) {
            LogUtil.e("loadFromObject error, ips:" + ips);
        }
    }

}
